import React from 'react';
import { observer } from 'mobx-react';
import { Card, Input, Button, Select, DatePicker, Form, Row, Col, Icon } from 'antd';
import OrderTable from './Table';
import store from './store';
import http from 'libs/http';
import categoryStore from '../course/category/store';

const { Option } = Select;
const { RangePicker } = DatePicker;
const FormItem = Form.Item;

// 表单项布局
const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

@observer
class OrderList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      order_no: '',
      student_name: '',
      parent_name: '',
      parent_phone: '',
      student_type: '',
      class_type: '',
      grade: '',
      status: '',
      payment_type: '',
      date_range: [],
      school_name: '',
      schoolOptions: [], // 学校列表选项
    };
  }

  componentDidMount() {
    this.fetchSchoolList();
    
    // 订阅store数据变化，用于调试
    this.unsubscribe = store.subscribe(() => {
      console.log('store filters changed:', store.filters);
    });
  }
  
  componentWillUnmount() {
    // 取消订阅
    if (this.unsubscribe) {
      this.unsubscribe();
    }
  }

  // 获取学校列表
  fetchSchoolList = () => {
    // 从 categoryStore 获取学校数据
    if (categoryStore.records.length > 0) {
      // 如果已有数据，直接使用
      console.log('从缓存获取学校数据:', categoryStore.records);
      this.processSchoolData(categoryStore.records);
    } else {
      // 否则从API获取
      categoryStore.fetchRecords()
        .then(() => {
          console.log('从API获取学校数据:', categoryStore.records);
          this.processSchoolData(categoryStore.records);
        })
        .catch(error => {
          console.error('获取学校列表失败:', error);
          // 加载失败时使用默认数据
          this.useDefaultSchoolData();
        });
    }
  }
  
  // 处理学校数据
  processSchoolData = (data) => {
    if (!Array.isArray(data)) {
      console.error('学校数据不是数组:', data);
      this.useDefaultSchoolData();
      return;
    }
    
    // 提取和规范化学校数据
    const schoolMap = new Map(); // 使用Map进行去重
    
    data.forEach(item => {
      const schoolName = item.school || item.name || '';
      if (schoolName && !schoolMap.has(schoolName)) {
        schoolMap.set(schoolName, {
          id: item.id,
          name: schoolName,
          value: schoolName
        });
      }
    });
    
    // 转换为数组
    const schoolOptions = Array.from(schoolMap.values());
    
    console.log('处理后的学校数据(已去重):', schoolOptions);
    this.setState({ schoolOptions });
  }

  // 使用默认学校数据（当API调用失败时）
  useDefaultSchoolData = () => {
    const defaultSchools = [
      { id: 1, name: '上海市第一中学', value: '上海市第一中学' },
      { id: 2, name: '上海市第二中学', value: '上海市第二中学' },
      { id: 3, name: '上海市第三中学', value: '上海市第三中学' },
      { id: 4, name: '上海市实验学校', value: '上海市实验学校' },
      { id: 5, name: '复旦大学附属中学', value: '复旦大学附属中学' }
    ];
    this.setState({ schoolOptions: defaultSchools });
  }

  handleInputChange = (field, value) => {
    console.log(`设置${field}字段:`, value);
    this.setState({ [field]: value });
    store.filters[field] = value;
  }

  handleSearch = () => {
    console.log('搜索条件:', this.state);
    
    // 确保学校名称正确设置到 store.filters
    if (this.state.school_name) {
      console.log('设置学校搜索条件:', this.state.school_name);
    }
    
    store.setFilters(this.state);
    console.log('store过滤条件:', store.filters);
    
    store.fetchRecords();
  };

  handleReset = () => {
    this.setState({
      order_no: '',
      student_name: '',
      parent_name: '',
      parent_phone: '',
      student_type: '',
      class_type: '',
      grade: '',
      status: '',
      payment_type: '',
      date_range: [],
      school_name: '',
    });
    store.resetFilters();
    store.fetchRecords();
  };

  render() {
    return (
      <Card>
        <Form layout="horizontal">
          <div style={{ marginBottom: 16 }}>
            <Row gutter={16}>
              <Col span={6}>
                <FormItem label="订单编号" {...formItemLayout}>
                  <Input 
                    placeholder="请输入订单编号" 
                    value={this.state.order_no}
                    onChange={e => this.handleInputChange('order_no', e.target.value)}
                    allowClear 
                  />
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label="学生姓名" {...formItemLayout}>
                  <Input 
                    placeholder="请输入学生姓名" 
                    value={this.state.student_name}
                    onChange={e => this.handleInputChange('student_name', e.target.value)}
                    allowClear 
                  />
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label="家长姓名" {...formItemLayout}>
                  <Input 
                    placeholder="请输入家长姓名" 
                    value={this.state.parent_name}
                    onChange={e => this.handleInputChange('parent_name', e.target.value)}
                    allowClear 
                  />
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label="家长手机" {...formItemLayout}>
                  <Input 
                    placeholder="请输入家长手机" 
                    value={this.state.parent_phone}
                    onChange={e => this.handleInputChange('parent_phone', e.target.value)}
                    allowClear 
                  />
                </FormItem>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={6}>
                <FormItem label="学校名称" {...formItemLayout}>
                  <Select 
                    placeholder="请选择学校" 
                    value={this.state.school_name}
                    onChange={value => this.handleInputChange('school_name', value)}
                    style={{ width: '100%' }}
                    getPopupContainer={trigger => trigger.parentNode}
                    allowClear
                    showSearch
                    optionFilterProp="children"
                  >
                    {this.state.schoolOptions.map(school => (
                      <Option key={school.id} value={school.value}>
                        {school.name}
                      </Option>
                    ))}
                  </Select>
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label="学员类型" {...formItemLayout}>
                  <Select 
                    placeholder="请选择学员类型" 
                    value={this.state.student_type}
                    onChange={value => this.handleInputChange('student_type', value)}
                    style={{ width: '100%' }}
                    getPopupContainer={trigger => trigger.parentNode}
                    allowClear
                  >
                    <Option value="文化生">文化生</Option>
                    <Option value="艺术生">艺术生</Option>
                    <Option value="体育生">体育生</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label="上课类型" {...formItemLayout}>
                  <Select 
                    placeholder="请选择上课类型" 
                    value={this.state.class_type}
                    onChange={value => this.handleInputChange('class_type', value)}
                    style={{ width: '100%' }}
                    getPopupContainer={trigger => trigger.parentNode}
                    allowClear
                  >
                    <Option value="in_school">校内上课</Option>
                    <Option value="out_school">校外上课</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label="年级" {...formItemLayout}>
                  <Select 
                    placeholder="请选择年级" 
                    value={this.state.grade}
                    onChange={value => this.handleInputChange('grade', value)}
                    style={{ width: '100%' }}
                    getPopupContainer={trigger => trigger.parentNode}
                    allowClear
                  >
                    <Option value="grade_1">高一</Option>
                    <Option value="grade_2">高二</Option>
                    <Option value="grade_3">高三</Option>
                  </Select>
                </FormItem>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={6}>
                <FormItem label="订单状态" {...formItemLayout}>
                  <Select 
                    placeholder="请选择订单状态" 
                    value={this.state.status}
                    onChange={value => this.handleInputChange('status', value)}
                    style={{ width: '100%' }}
                    getPopupContainer={trigger => trigger.parentNode}
                    allowClear
                  >
                    <Option value="pending">待支付</Option>
                    <Option value="paid">已支付</Option>
                    <Option value="cancelled">已取消</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label="支付方式" {...formItemLayout}>
                  <Select 
                    placeholder="请选择支付方式" 
                    value={this.state.payment_type}
                    onChange={value => this.handleInputChange('payment_type', value)}
                    style={{ width: '100%' }}
                    getPopupContainer={trigger => trigger.parentNode}
                    allowClear
                  >
                    <Option value="wechat">微信支付</Option>
                    <Option value="offline">线下汇款</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem label="创建时间" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
                  <RangePicker 
                    style={{ width: '100%' }} 
                    value={this.state.date_range}
                    onChange={value => this.handleInputChange('date_range', value)}
                    getPopupContainer={trigger => trigger.parentNode}
                  />
                </FormItem>
              </Col>
            </Row>
            
            {/* 操作按钮区域 - 改进布局 */}
            <Row>
              <Col span={24} style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 16 }}>
                {/* 搜索操作按钮组 */}
                <Button.Group style={{ marginRight: 16 }}>
                  <Button type="primary" onClick={this.handleSearch}>
                    <Icon type="search" />搜索
                  </Button>
                  <Button onClick={this.handleReset}>
                    <Icon type="reload" />重置
                  </Button>
                </Button.Group>
                
                {/* 数据操作按钮组 */}
                <Button.Group>
                  <Button 
                    onClick={store.fetchRecords} 
                    icon="sync"
                  >
                    刷新
                  </Button>
                  <Button 
                    onClick={() => store.exportToExcel('all')} 
                    icon="download"
                  >
                    导出全部
                  </Button>
                  <Button 
                    onClick={() => store.exportToExcel('selected')} 
                    icon="file-excel"
                    disabled={!store.selectedRowKeys || store.selectedRowKeys.length === 0}
                  >
                    导出已选({store.selectedRowKeys ? store.selectedRowKeys.length : 0})
                  </Button>
                </Button.Group>
              </Col>
            </Row>
          </div>
        </Form>
        <OrderTable />
      </Card>
    );
  }
}

export default OrderList;
